import { enterBig, createWS } from '@/api/index.js'
import { messageBody, wsSend, transTimestamp } from '@/utils/index.js'
import { Ws } from './model.js'
import { Dialog } from 'vant'
export default {
  components: {
    [Dialog.Component.name]: Dialog.Component
  },
  data() {
    return {
      bigId: '',
      meetingId: '',
      waiterId: '',
      bigSocketTask: {},
      socketTask: {},
      bigwsOpen: false,
      wsOpen: false,
      timeout: 4000,
      interval: 8000,
      clientTimer: null,
      severTimer: null,
      chatTimer: null,
      keepTime: 180000,
      smartTalkerType: '',
      smartTalkerId: '',
      bigTalkerType: '',
      bigTalkerId: '',
      waiterType: '',
      reconnectNum: 0,
      reconnectLimit: 5,
      serviceInter: false, //客服接入
      reconcatToast: false,
      queueNum: null //进入大会场等待人数
    }
  },
  filters: {
    timestamp(val) {
      return new Date(val).toLocaleTimeString()
    }
  },
  watch: {
    wsOpen: {
      //监听小会场建立成功
      handler(newVal) {
        if (newVal) {
          this.socketTask.addEventListener('message', e => {
            this.onMessage(e)
          })
        }
      }
    },
    reconnectNum(val) {
      if (val === 0) {
        this.$toast.clear()
      } else {
        this.$toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true,
          message: '重连中'
        })
      }
    }
  },
  methods: {
    /*创建大会场*/
    creatBigMeeting() {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: '连接中'
      })
      let token = window.sessionStorage.getItem('token') || ''
      let ticket = window.sessionStorage.getItem('ticket') || ''
      let IM_UUID = ''
      let type = 4
      if (ticket) {
        type = 2
      } else if (!ticket && !token) {
        type = 4
      } else {
        type = 3
      }
      if (type === 4) {
        IM_UUID = window.localStorage.getItem('IM_UUID') || ''
      }
      const params = {
        type,
        token,
        ticket,
        IM_UUID
      }
      enterBig(params)
        .then(res => {
          const { data } = res
          this.bigId = data.mainId
          this.bigTalkerType = data.userType
          this.bigTalkerId = data.token
          this.ID = data.token
          if (data.userType == '4') {
            window.localStorage.setItem('IM_UUID', data.token)
          }
          this.$toast.clear()
          if (this.bigId) {
            this.createWebsocket()
          } else {
            this.$toast('大会场接入失败')
          }
        })
        .catch(() => {
          this.$toast.clear()
          this.$toast('大会场接入失败')
        })
    },
    // ws连接
    async createWebsocket() {
      const params = `?talkerType=${this.bigTalkerType}&talkerId=${this.bigTalkerId}&meetingId=${this.bigId}`
      this.bigSocketTask = await createWS(params)
      this.wsListener()
    },
    // ws监听
    wsListener() {
      this.bigSocketTask.addEventListener('open', () => {
        this.bigwsOpen = true
        this.reconnectNum = 0
        this.heartStart()
        console.log('大会场连接上了')
      })
      this.bigSocketTask.addEventListener('message', e => {
        this.heartStart()
        let { data } = e
        const message = JSON.parse(data)
        // 正常消息
        let base = {
          id: message.serial,
          time: message.sTime
        }
        let params = {}
        if (message.type === '0x20') {
          //主会场欢迎辞
          this.smartTalkerType = message.content.talkerType
          this.smartTalkerId = message.content.talkerId
          this.ID = this.smartTalkerId
        }
        if (message.type === '0x66' || message.type === '0x61') {
          this.queueNum = 0
          //自动分配
          if (this.socketTask && this.socketTask.wsOpen) {
            //先断开原来连接
            this.socketTask.close()
          }
          this.meetingId = message.content.smallMeetingId
          this.waiterId = message.content.waiterId
          this.waiterType = message.content.waiterType
          const s = `?talkerType=${this.smartTalkerType}&talkerId=${this.smartTalkerId}&meetingId=${this.meetingId}&otherId=${this.waiterId}`
          const wsInstance = new Ws(s)
          wsInstance.createWebsocket()
          this.socketTask = wsInstance.socketTask
          this.socketTask.addEventListener('open', () => {
            this.wsOpen = true
            console.log('小会场连接上了')
          })
          this.socketTask.addEventListener('close', () => {
            this.wsOpen = false
            console.log('小会场关闭了')
          })
        }
        if (message.type === '0x72') {
          this.queueNum = Number(message.content)
        }
        if (message.type === '0x69' || message.type === '0x71' || message.type === '0x73' || message.type === '0x74') {
          params = {
            type: 'user',
            uid: 'message.content.talkerId',
            content: {
              text: message.content
            },
            talkType: 'text'
          }
        }
        let showData = messageBody({ ...base, ...params })
        this.screenMsg(showData)
      })
      this.bigSocketTask.addEventListener('close', () => {
        console.log('大会场关闭了')
      })
    },
    heartStart() {
      this.serverTimer && clearTimeout(this.serverTimer)
      this.clientTimer && clearInterval(this.clientTimer)
      this.clientTimer = setInterval(() => {
        //发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
        let params = {
          contentType: '0x25',
          content: ''
        }
        wsSend(this.bigSocketTask, params)
        //定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
        this.serverTimer && clearTimeout(this.serverTimer)
        this.serverTimer = setTimeout(() => {
          this.bigSocketTask.close()
          this.reConnect()
        }, this.timeout)
      }, this.interval)
    },
    reConnect() {
      this.chatTimer && clearTimeout(this.chatTimer) //重连操作时清楚静待超时计时器
      if (this.reconnectNum >= this.reconnectLimit) {
        this.clearTimer()
        this.reconnectNum = 0
        Dialog.alert({
          message: '连接失败，请退出重试',
          confirmButtonColor: '#1989fa',
          className: 'cust-alert'
        }).then(() => {
          if (window.KDS_Native && window.KDS_Native.shutCurrentPage) {
            window.KDS_Native.shutCurrentPage()
          } else {
            window.location.reload()
          }
        })
        return
      }
      this.reconnectNum++
      this.createWebsocket()
    },
    onMessage(e) {
      this.meetingTimeout()
      const { data } = e
      const message = JSON.parse(data)
      // 正常消息
      let base = {
        id: message.serial,
        time: message.sTime
      }
      let params = {}
      if (message.type === '0x27') {
        this.editTitle(0)
      }
      if (message.type === '0x28') {
        this.editTitle(1)
      }
      if (message.type === '0x30' || message.type === '0x31') {
        //欢迎、告别辞
        params = {
          type: 'system',
          uid: '9527_',
          content: {
            text: message.content.word
          },
          talkType: 'text'
        }
      }
      if (message.type === '0x26') {
        this.socketTask.close()
        this.bigSocketTask.close()
        this.clearTimer()
        Dialog.alert({
          message: '您长时间未响应，连接暂时断开',
          confirmButtonColor: '#1989fa',
          className: 'cust-alert'
        }).then(() => {
          if (window.KDS_Native && window.KDS_Native.shutCurrentPage) {
            window.KDS_Native.shutCurrentPage()
          } else {
            window.location.reload()
          }
        })
      }
      if (message.type === '0x78') {
        this.serviceInter = true
        const channelmsg = {
          //发送渠道消息
          contentType: '0x75',
          content: this.channel
        }
        this.wsOpen && wsSend(this.socketTask, channelmsg)
        return
      }
      if (message.type === '0x65' || message.type === '0x34') {
        //客服关闭窗口
        this.socketTask.close()
        this.bigSocketTask.close()
        this.clearTimer()
        Dialog.alert({
          message: '客服结束了会话, 希望再次为您服务!',
          confirmButtonColor: '#1989fa',
          className: 'cust-alert'
        }).then(() => {
          if (window.KDS_Native && window.KDS_Native.shutCurrentPage) {
            window.KDS_Native.shutCurrentPage()
          } else {
            window.location.reload()
          }
        })
      }
      if (message.type === '0x79') {
        //客服欢迎辞
        //消息客服发的欢迎辞之前穿插一条时间
        params = {
          type: 'system',
          uid: message.content.talkerId,
          content: {
            text: transTimestamp(message.sTime)
          },
          talkType: 'text'
        }
        this.screenMsg(messageBody({ ...base, ...params }))
      }
      if (message.type === '0x41' || message.type === '0x79') {
        //文字对话且不是自己说的话
        params = {
          type: 'user',
          uid: message.content.talkerId,
          content: {
            text: message.content.word
          },
          talkType: 'text'
        }
      }
      if (message.type === '0x45') {
        //图片对话且不是自己说的话
        params = {
          type: 'user',
          uid: message.content.talkerId,
          content: {
            url: message.content.word
          },
          talkType: 'img'
        }
      }
      if (message.type === '0x62') {
        // 发送工具连接
        params = {
          type: 'link',
          uid: message.content.talkerId,
          content: {
            link: JSON.parse(message.content.word)
          },
          talkType: 'link'
        }
      }
      if (message.type === '0x76' || message.type === '0x77') {
        //验证消息
        params = {
          type: 'system',
          uid: message.content.talkerId,
          content: {
            text: message.content.word
          },
          talkType: 'text'
        }
      }
      let showData = messageBody({ ...base, ...params })
      this.screenMsg(showData)
    },
    // 计时关闭小会场（静待超时）
    meetingTimeout() {
      this.chatTimer && clearTimeout(this.chatTimer)
      this.chatTimer = setTimeout(() => {
        let params = {
          contentType: '0x26',
          content: '用户静待超时'
        }
        wsSend(this.socketTask, params)
      }, this.keepTime)
    },
    // 更改标题
    editTitle(event) {
      //暂无实现
      if (event == 0) {
        document.getElementsByTagName('title')[0].innerText = '对方正在输入...'
      } else {
        document.getElementsByTagName('title')[0].innerText = '客服咨询'
      }
    },
    clearTimer() {
      this.clientTimer && clearInterval(this.clientTimer)
      this.serverTimer && clearTimeout(this.serverTimer)
      this.chatTimer && clearTimeout(this.chatTimer)
    }
  }
}
